package com.yuanian.wf.annotation.scan;

import com.yuanian.wf.exception.WfException;
import com.yuanian.wf.pojo.model.ProcessManager;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Set;
/**
 * WfProcessKey注解的注入器
 */
public class ProcessBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        ProcessClassPathScanningCandidateComponentProvider processClassPathScanningCandidateComponentProvider = new ProcessClassPathScanningCandidateComponentProvider();
        Set<BeanDefinition> wfProcessKeySet = processClassPathScanningCandidateComponentProvider.findCandidateComponents("com.yuanian");
        for (BeanDefinition wfProcessKeyBeanDefinition : wfProcessKeySet) {
            try {
                //获取带WfProcessKey注解类字节码
                Class clz = Class.forName(wfProcessKeyBeanDefinition.getBeanClassName());
                String processKey = ProcessManager.addProcess(clz);
                if (processKey != null) {
                    //放入spring容器
                    beanDefinitionRegistry.registerBeanDefinition("wf" + "$" + processKey, wfProcessKeyBeanDefinition);
                }
            } catch (Exception e) {
                throw new WfException("工作流初始化失败，" + e.getMessage());
            }
        }
    }

}
